package czk.concrent.enjoyModelWithNotLock.unsafe;


import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * 获取底层对象unsafe,可以直接操作内存
 * @Author:ChenZhangKun
 * @Date: 2020/6/20 17:45
 */
public class UnsafeDemo {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        // 只能通过反射获取对象
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        // 设置私有访问为true
        theUnsafe.setAccessible(true);
        // 获取对象，静态字段不需要传入对象
        Unsafe unsafe=(Unsafe) theUnsafe.get(null);
        // 打印对象
        System.out.println(unsafe.getClass());


        // 获取域的偏移地址
        long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
        System.out.println(idOffset);
        long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));
        // 进行cas赋值
        Teacher teacher=new Teacher();
        unsafe.compareAndSwapInt(teacher,idOffset,0,1);
        unsafe.compareAndSwapObject(teacher,nameOffset,null,"陈彰坤");
        System.out.println(teacher);
    }
}
class Teacher{
    // volatile保证可见性
    volatile String name;
    volatile int id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }
}
